<?php
namespace  app\admin\controller;
use think\Controller;
use think\Db;
use think\Request;
use app\admin\model\Admin_model;
Class Childusers extends Controller{
    function __construct(Request $request = null)
    {
        parent::__construct($request);
        if(session('user')) {
            $user=session('user');
            $admin_model=new Admin_model();
            $fun=$admin_model->get_rolefunction($user['role']);
            $this->assign('fun',$fun);
            $this->assign('active','子账户管理');
        }else{
            $this->redirect('index/login/index');
        }
    }
    function  child_users_list(){
        $this->assign('title','子账户列表');
        return $this->fetch();
    }
    function  get_child_users(){
        $user=session('user');
        $where=array();
        if ($user['role']!=0){
            $where['attr_user_id']=$user['id'];
        }
        if($_GET['search']){
            $where['name']=array('like','%'.$_GET['search'].'%');
        }
        $total=Db::name('child_user')->where($where)->count();
        $rows=Db::name('child_user')->limit($_GET['offset'],$_GET['limit'])->where($where)->order($_GET['sort'],$_GET['order'])->select();
        foreach ($rows as &$row){
            $uid=Db::name('user')->field('id') ->where('username',$row['name'])->find();
            $row['operate']='<a  onclick="reset_pwd('.$uid['id'].')" class="btn btn-link">重置密码</a><a href="#" class="btn btn-link">模拟登录</a>
            <a href="#" class="btn btn-link">删除此用户</a> ';
        }
        echo  json_encode(array('total'=>$total,'rows'=>$rows));
    }

    function  add_child_users(){
        $user=session('user');
        if(request()->isPost()) {
            $data = input('post.');
            unset($data['chi_pwd_check']);
            $adv = Db::name('child_user')->where('name', $data['name'])->select();
            $zh = Db::name('user')->where('username', $data['name'])->select();
            if (!empty($adv) || !empty($zh)) {
                return array('code' => 0, 'msg' => '账户名称已被使用');
            } else {
                $data['attr_user_id'] = $user['id'];
                $id = Db::name('child_user')->insertGetId($data);
                $user = array('username' => $data['name'], 'password' => $data['chi_pwd'], 'role' => ZZH);
                $uid = Db::name('user')->insert($user);
                if ($id && $uid) {
                    return array('code' => 1, 'msg' => '新增成功', 'url' => url('child_users_list'));
                } else {
                    return array('code' => 0, 'msg' => '新增失败');
                }

            }
        }
        $this->assign('title','添加子账户');
        return $this->fetch();
    }
}